﻿using Coleotrack.Data;
using Coleotrack.Data.Maps;
using Coleotrack.Service.Contracts;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using StructureMap.Configuration.DSL;

namespace Coleotrack.Service.Registration
{
    public class NHibernateRegistry : Registry
    {
        public NHibernateRegistry(string connectionString, bool createSchema)
        {
            For<IMappingConfiguration>().Singleton().Use<SqlServerMappingConfiguration>();
            For<IExposeConfiguration>().Singleton().Use(new ExposeConfiguration(createSchema));
            For<ISqlServerPersistenceConfigurer>().Singleton().Use<SqlServerPersistenceConfigurer>();
            For<ISqlServerConfiguration>().Singleton().Use<SqlServerConfiguration>();
            For<ISessionFactory>().Singleton().Use(x => 
                x.GetInstance<ISqlServerConfiguration>()
                .GetConfiguration
                (
                    connectionString, 
                    x.GetInstance<ISqlServerPersistenceConfigurer>(), 
                    x.GetInstance<IExposeConfiguration>(),
                    x.GetInstance<IMappingConfiguration>()
                )
                .BuildSessionFactory());
            For<ISession>().HybridHttpOrThreadLocalScoped().Use(x => x.GetInstance<ISessionFactory>().OpenSession());
            For<INHibernateUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<NHibernateUnitOfWork>();
        }
    }
}
